import sqlite3
import Hostini
import logging
from Login import *

##############
#author:张子路#
##############

class SqlInformation():
    def __init__(self):
        try:
            self.HostConfigRead=Hostini.GetHostConfig()
        except Exception as e:
            logging.error("配置项读取文件连接出错 {0}".format(e), exc_info=True)
        try:
            self.conn = sqlite3.connect("./DEMO.db")
            self.cur = self.conn.cursor()
        except Exception as e:
            logging.error("数据库读取创建出错 {0}".format(e), exc_info=True)
        try:
            self.cur.execute('DROP TABLE IF EXISTS ConfigInformation')
        except Exception as e:
            logging.error("数据库原表单删除出错 {0}".format(e), exc_info=True)        #删除原来的核查结果
        try:             #创建新的表
            sql='CREATE TABLE IF NOT EXISTS ConfigInformation(id INTEGER PRIMARY KEY, ' \
                                                              'item_name TEXT,' \
                                                              'is_evalued INTEGER,' \
                                                              'eval_result TEXT,' \
                                                              'eval_method TEXT,' \
                                                              'eval_para TEXT,' \
                                                              'cur_val TEXT,' \
                                                              'cmpr_method TEXT,' \
                                                              'rel_val TEXT,' \
                                                              'hrdn_val TEXT,' \
                                                              'vis_trans TEXT,' \
                                                              'memo TEXT)'
            self.cur.execute(sql)
        except Exception as e:
            logging.error("数据库表单创建出错 {0}".format(e), exc_info=True)

    def CloseSql(self):        #关闭数据库
        try:
            self.conn.close()
        except Exception:
            print('关闭数据库出错。')

    def InSert(self,StanderdConfigList):
        CheckList=[]
        date=[]
        try:
            for items in StanderdConfigList:
                CheckList.append([items[1],items[2]])
        except Exception as e:
            logging.error("创建检查配置项出错 {0}".format(e), exc_info=True)
        try:
            HostConfigList=self.HostConfigRead.GetConfig(CheckList)       #获取相应的安全策略值
        except Exception as e:
            logging.error("获取本机配置项出错 {0}".format(e), exc_info=True)
        for items in StanderdConfigList:
            try:
                for Hostitems in HostConfigList:         #按照规范生成要插入数据库的数据
                    if(Hostitems[0]==items[1] and Hostitems[1]==items[2]):
                        date.append((None,items[0],None,None,'ini',str((items[1],items[2])),Hostitems[2],str(items[3]),str(items[4]),str(items[5]),None,None))
                        break
            except Exception as e:
                logging.error("获取本机配置项出错 {0}".format(e), exc_info=True)
        try:
            self.conn.executemany('INSERT INTO ConfigInformation VALUES (?,?,?,?,?,?,?,?,?,?,?,?)',date)      #将检测结果输入数据库
            self.conn.commit()
        except Exception as e:
            logging.error("数据提交出错 {0}".format(e), exc_info=True)
        finally:
            return date      #返回结果

    def FindAll(self):
        try:        #查询数据库中的数据
            self.cur.execute('select * from ConfigInformation')
            for item in self.cur.fetchall():
                print(item)
        except Exception as e:
            logging.error("数据查询出错 {0}".format(e), exc_info=True)





if __name__ =='__main__':
    login=LoginStart()
    login.start()
    '''
    si=SqlInformation()
    sl=[['账户安全核查','System Access','LockoutBadCount',['bt'],['15'],'15'],
        ['账户安全核查','System Access','RequireLogonToChangePassword',['st','not equ'],['10','0'],'10'],
        ['账户安全核查','System Access','ForceLogoffWhenHourExpire',['bt'],['15'],'15']]
    re=si.InSert(sl)
    si.FindAll()
    si.CloseSql()
    '''